package cc.dullsky.article;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;

import cc.dullsky.common.Constant;
import cc.dullsky.common.model.Article;
import cc.dullsky.common.model.ArticleTag;
import cc.dullsky.common.model.Comment;
import cc.dullsky.common.model.Tag;
import cc.dullsky.common.model.User;
import cc.dullsky.common.model.Visitor;
import cc.dullsky.util.RegexpUtil;

public class ArticleController extends Controller {
	/**
	 * 进入文章页面
	 */
	public void index() {
		Integer articleId = getParaToInt("id");
		Article article = Article.dao.findById(articleId);
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append("<div class='ibox'><div class='ibox-content'><div class='pull-right'>");
		List<ArticleTag> articleTags = ArticleTag.dao.findByArticleId(article.getId());
		for (ArticleTag articleTag : articleTags) {
			stringBuilder.append("<button class='btn btn-white btn-xs' type='button'>");
			stringBuilder.append(Tag.dao.findById(articleTag.getTagId()).getName());
			stringBuilder.append("</button>&nbsp;");
			// tagMap.put("tagId",
			// Tag.dao.findById(articleTag.getTagId()).getId());
		}
		stringBuilder.append("</div><div class='text-center article-title' style='margin: 40px 0 25px;'><h1>").append(article.getTitle())
				.append("</h1></div><div class='markdown-body editormd-html-preview'>").append(article.getHtmlcontent())
				.append("</div><span class='pull-right text-muted'><i class='fa fa-clock-o'></i>&nbsp;").append(article.getCreatetime())
				.append("</span><hr></div></div>");
		if (getRequest().getHeader("X-PJAX") == null) {
			setAttr("article", stringBuilder.toString());
		} else {
			renderHtml(stringBuilder.toString());
		}
	}

	/**
	 * ajax获取近期文章
	 */
	public void getRecentArticles() {
		List<Article> articles = Article.dao.findRecentArticles();
		List<Map<String, Object>> list = new ArrayList<>();
		for (Article article : articles) {
			Map<String, Object> map = new HashMap<>();
			map.put("id", article.getId());
			map.put("title", article.getTitle());
			map.put("count", Comment.dao.countByArticleId(article.getId()));
			list.add(map);
		}
		renderJson(list);
	}

	/**
	 * ajax获取分页文章列表
	 */
	public void getArticleList() {
		int pageNumber = 1;
		if (getParaToInt("pageNumber") != null) {
			pageNumber = getParaToInt("pageNumber");
		}
		Page<Article> page = Article.dao.paginate(pageNumber, Constant.ARTICLE_PAGE_SIZE);
		List<Article> articles = page.getList();
		List<Map<String, Object>> list = new ArrayList<>();
		for (Article article : articles) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", article.getId());
			map.put("title", article.getTitle());
			map.put("userId", article.getUserId());
			map.put("author", User.dao.findById(article.getUserId()).getNickname());
			map.put("createTime", article.getCreatetime());
			String textContent = RegexpUtil.getTextFormHtml(article.getHtmlcontent());
			String abstractContent = textContent.length() > 200 ? textContent.substring(0, 200) : textContent;
			map.put("abstractContent", abstractContent);
			List<ArticleTag> articleTags = ArticleTag.dao.findByArticleId(article.getId());
			List<Map<String, Object>> tags = new ArrayList<>();
			for (ArticleTag articleTag : articleTags) {
				Map<String, Object> tagMap = new HashMap<>();
				tagMap.put("tagId", Tag.dao.findById(articleTag.getTagId()).getId());
				tagMap.put("tagName", Tag.dao.findById(articleTag.getTagId()).getName());
				tags.add(tagMap);
			}
			map.put("tags", tags);
			map.put("commentCount", Comment.dao.countByArticleId(article.getId()));
			map.put("visitorCount", Visitor.dao.countByArticleId(article.getId()));
			list.add(map);
		}
		Page<Map<String, Object>> newPage = new Page<>(list, page.getPageNumber(), page.getPageSize(), page.getTotalPage(), page.getTotalRow());
		renderJson(newPage);
	}

	/**
	 * ajax文章归档
	 */
	public void getArticleArchives() {
		List<Article> articles = Article.dao.findAll();
		Date firstDate = articles.get(0).getCreatetime();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(firstDate);
		int firstYear = calendar.get(Calendar.YEAR);
		int firstMonth = calendar.get(Calendar.MONTH);
		Date lastDate = articles.get(articles.size() - 1).getCreatetime();
		calendar.setTime(lastDate);
		int lastYear = calendar.get(Calendar.YEAR);
		int lastMonth = calendar.get(Calendar.MONTH);
		int len = (lastYear - firstYear) * 12 + (lastMonth - firstMonth) + 1;
		List<Map<String, Object>> list = new ArrayList<>();
		for (int i = 0; i < len; i++) {
			if (firstMonth > 12) {
				firstMonth = 0;
				firstYear++;
			}
			Map<String, Object> map = new HashMap<>();
			map.put("content", firstYear + "年" + Constant.MONTH[firstMonth] + "月");
			map.put("count", Article.dao.countByMonth(firstYear, firstMonth));
			map.put("year", firstYear);
			map.put("month", firstMonth);
			list.add(map);
			firstMonth++;
		}
		Collections.reverse(list);
		renderJson(list);
	}

	/**
	 * ajax获取文章
	 */
	public void getArticle() {
		System.err.println(getRequest().getHeader("X-PJAX"));// true/null
		if (getRequest().getHeader("X-PJAX") == null) {

		} else {
			Integer articleId = getParaToInt("articleId");
			Article article = Article.dao.findById(articleId);
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.append("<div class='ibox'><div class='ibox-content'><div class='pull-right'>");
			List<ArticleTag> articleTags = ArticleTag.dao.findByArticleId(article.getId());
			for (ArticleTag articleTag : articleTags) {
				stringBuilder.append("<button class='btn btn-white btn-xs' type='button'>");
				stringBuilder.append(Tag.dao.findById(articleTag.getTagId()).getName());
				stringBuilder.append("</button>&nbsp;");
				// tagMap.put("tagId",
				// Tag.dao.findById(articleTag.getTagId()).getId());
			}
			stringBuilder.append("</div><div class='text-center article-title' style='margin: 40px 0 25px;'><h1>").append(article.getTitle())
					.append("</h1></div><div class='markdown-body editormd-html-preview'>").append(article.getHtmlcontent())
					.append("</div><span class='pull-right text-muted'><i class='fa fa-clock-o'></i>&nbsp;").append(article.getCreatetime())
					.append("</span><hr>");
			// map.put("id", article.getId());
			renderHtml(stringBuilder.toString());
		}
	}
}
